<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="1" data-page-identification="x_hb0xe6o0k2">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
            <div class="condition-builder">
                <a-button @click="save"> 保存 </a-button>
                <div class="condition-tree">
                    <div v-for="(group, index) in conditionTree.children" :key="group.key">
                        <template v-if="group.children && group.children.length">
                            <div class="group-operator" @click="toggleOperator(group)">
                                {{ group.operator === 'AND' ? '且' : '或' }}
                            </div>
                            <div class="group-children">
                                <div v-for="(item, idx) in group.children" :key="item.key" class="condition-item">
                                    <template v-if="item.children">
                                        <!-- 嵌套组 -->
                                        <div>
                                            <span class="group-operator" @click="toggleOperator(item)">
                                                {{ item.operator === 'AND' ? '且' : '或' }}
                                            </span>
                                            <div class="group-children">
                                                <div
                                                    v-for="(child, childIdx) in item.children"
                                                    :key="child.key"
                                                    class="condition-item"
                                                >
                                                    <template v-if="!child.children">
                                                        <!-- 直接渲染表单 -->
                                                        <a-space>
                                                            <a-select
                                                                v-model:value="
                                                                    child.expression.filterCondition.filterColumnName
                                                                "
                                                                style="width: 100px"
                                                            >
                                                                <a-select-option
                                                                    v-for="col in columnData"
                                                                    :key="col.label"
                                                                    :value="col.value"
                                                                    >{{ col.label }}</a-select-option
                                                                >
                                                            </a-select>
                                                            <a-select
                                                                v-model:value="
                                                                    child.expression.filterCondition.conditionType
                                                                "
                                                                style="width: 100px"
                                                            >
                                                                <a-select-option
                                                                    v-for="t in typeData"
                                                                    :key="t.conditionType"
                                                                    :value="t.conditionType"
                                                                    >{{ t.title }}</a-select-option
                                                                >
                                                            </a-select>
                                                            <template
                                                                v-if="
                                                                    child.expression.filterCondition.conditionType ===
                                                                        'EQUALS' ||
                                                                    child.expression.filterCondition.conditionType ===
                                                                        'NOT_EQUALS'
                                                                "
                                                            >
                                                                <a-input
                                                                    v-model:value="
                                                                        child.expression.filterCondition.value
                                                                    "
                                                                    style="width: 100px"
                                                                />
                                                            </template>
                                                            <template v-else>
                                                                <a-input-number
                                                                    v-model:value="
                                                                        child.expression.filterCondition.value
                                                                    "
                                                                    style="width: 100px"
                                                                />
                                                                <a-select
                                                                    v-if="
                                                                        child.expression.filterCondition.conditionType.includes(
                                                                            'BETWEEN'
                                                                        )
                                                                    "
                                                                    v-model:value="
                                                                        child.expression.filterCondition.minType
                                                                    "
                                                                    style="width: 70px"
                                                                >
                                                                    <a-select-option value="GT">&gt;</a-select-option>
                                                                    <a-select-option value="GE">&gt;=</a-select-option>
                                                                </a-select>
                                                                <span
                                                                    v-if="
                                                                        child.expression.filterCondition.conditionType.includes(
                                                                            'BETWEEN'
                                                                        )
                                                                    "
                                                                    >值</span
                                                                >
                                                                <a-input-number
                                                                    v-if="
                                                                        child.expression.filterCondition.conditionType.includes(
                                                                            'BETWEEN'
                                                                        )
                                                                    "
                                                                    v-model:value="
                                                                        child.expression.filterCondition.value
                                                                    "
                                                                    style="width: 100px"
                                                                />
                                                                <a-select
                                                                    v-if="
                                                                        child.expression.filterCondition.conditionType.includes(
                                                                            'BETWEEN'
                                                                        )
                                                                    "
                                                                    v-model:value="
                                                                        child.expression.filterCondition.maxType
                                                                    "
                                                                    style="width: 70px"
                                                                >
                                                                    <a-select-option value="LT">&lt;</a-select-option>
                                                                    <a-select-option value="LE">&lt;=</a-select-option>
                                                                </a-select>
                                                            </template>
                                                        </a-space>
                                                        <a-button
                                                            type="link"
                                                            danger
                                                            @click="removeCondition(item.children, child)"
                                                            >删除</a-button
                                                        >
                                                    </template>
                                                </div>
                                                <a-button type="link" @click="addCondition(item)">添加条件</a-button>
                                                <a-button type="link" @click="addConditionGroup(item)"
                                                    >添加条件组</a-button
                                                >
                                                <a-button
                                                    type="link"
                                                    danger
                                                    @click="removeCondition(group.children, item)"
                                                    >删除组</a-button
                                                >
                                            </div>
                                        </div>
                                    </template>
                                    <template v-else>
                                        <!-- 直接渲染表单 -->
                                        <a-space>
                                            <a-select
                                                v-model:value="item.expression.filterCondition.filterColumnName"
                                                style="width: 100px"
                                            >
                                                <a-select-option
                                                    v-for="col in columnData"
                                                    :key="col.label"
                                                    :value="col.value"
                                                    >{{ col.label }}</a-select-option
                                                >
                                            </a-select>
                                            <a-select
                                                v-model:value="item.expression.filterCondition.conditionType"
                                                style="width: 100px"
                                            >
                                                <a-select-option
                                                    v-for="t in typeData"
                                                    :key="t.conditionType"
                                                    :value="t.conditionType"
                                                    >{{ t.title }}</a-select-option
                                                >
                                            </a-select>
                                            <template
                                                v-if="
                                                    item.expression.filterCondition.conditionType === 'EQUALS' ||
                                                    item.expression.filterCondition.conditionType === 'NOT_EQUALS'
                                                "
                                            >
                                                <a-input
                                                    v-model:value="item.expression.filterCondition.value"
                                                    style="width: 100px"
                                                />
                                            </template>
                                            <template v-else>
                                                <a-input-number
                                                    v-model:value="item.expression.filterCondition.value"
                                                    style="width: 100px"
                                                />
                                                <a-select
                                                    v-if="
                                                        item.expression.filterCondition.conditionType.includes(
                                                            'BETWEEN'
                                                        )
                                                    "
                                                    v-model:value="item.expression.filterCondition.minType"
                                                    style="width: 70px"
                                                >
                                                    <a-select-option value="GT">&gt;</a-select-option>
                                                    <a-select-option value="GE">&gt;=</a-select-option>
                                                </a-select>
                                                <span
                                                    v-if="
                                                        item.expression.filterCondition.conditionType.includes(
                                                            'BETWEEN'
                                                        )
                                                    "
                                                    >值</span
                                                >
                                                <a-input-number
                                                    v-if="
                                                        item.expression.filterCondition.conditionType.includes(
                                                            'BETWEEN'
                                                        )
                                                    "
                                                    v-model:value="item.expression.filterCondition.value"
                                                    style="width: 100px"
                                                />
                                                <a-select
                                                    v-if="
                                                        item.expression.filterCondition.conditionType.includes(
                                                            'BETWEEN'
                                                        )
                                                    "
                                                    v-model:value="item.expression.filterCondition.maxType"
                                                    style="width: 70px"
                                                >
                                                    <a-select-option value="LT">&lt;</a-select-option>
                                                    <a-select-option value="LE">&lt;=</a-select-option>
                                                </a-select>
                                            </template>
                                        </a-space>
                                        <a-button type="link" danger @click="removeCondition(group.children, item)"
                                            >删除</a-button
                                        >
                                    </template>
                                </div>
                                <div class="action-row">
                                    <a-button type="link" @click="addCondition(group)">添加条件</a-button>
                                    <a-button type="link" @click="addConditionGroup(group)">添加条件组</a-button>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
            <!-- end vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    // 字段选项
    const columnData = [
        { label: '字段1', value: 'FIELD_1' },
        { label: '字段2', value: 'FIELD_2' },
        { label: '字段3', value: 'FIELD_3' },
        { label: '系统用户', value: 'SYSTEM_USER' }
    ]

    // 条件类型选项
    const typeData = [
        { conditionType: 'EQUALS', title: '等于' },
        { conditionType: 'NOT_EQUALS', title: '不等于' },
        { conditionType: 'GT', title: '大于' },
        { conditionType: 'LT', title: '小于' },
        { conditionType: 'BETWEEN', title: '介于' },
        { conditionType: 'NOT_BETWEEN', title: '不介于' },
        { conditionType: 'CONTAIN', title: '包含' }
    ]

    // 简单的 key 自增函数替代 uuid
    let keyCounter = 0
    function createKey() {
        return `k_${++keyCounter}`
    }

    // 创建一个条件对象
    const createCondition = () => ({
        key: createKey(),
        expression: {
            filterType: 'CONDITION',
            filterCondition: {
                filterColumnName: '',
                type: 'SYSTEM',
                conditionType: '',
                value: '',
                dateFormat: ''
            }
        }
    })

    // 创建一个条件组
    const createGroup = () => ({
        key: createKey(),
        operator: 'AND',
        children: [createCondition()]
    })

    // 根条件树结构
    const conditionTree = reactive({
        operator: 'AND',
        children: [createGroup()]
    })

    // 添加条件
    function addCondition(group) {
        group.children.push(createCondition())
    }

    // 添加条件组
    function addConditionGroup(group) {
        group.children.push(createGroup())
    }

    // 删除某个条件或组
    function removeCondition(list, item) {
        if (list.length == 1) {
            message.info('最少有一个')
            return
        }
        const index = list.indexOf(item)
        if (index !== -1) list.splice(index, 1)
    }

    // 切换“且/或”
    function toggleOperator(group) {
        group.operator = group.operator === 'AND' ? 'OR' : 'AND'
    }
    function save() {
        console.log(conditionTree)
    }
</script>

<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .condition-tree {
        padding: 12px;
        background-color: #fff;
        border: 1px solid #eee;
    }
    .group-operator {
        margin-bottom: 8px;
        font-weight: bold;
        cursor: pointer;
        color: #1677ff;
    }
    .group-children {
        margin-left: 16px;
        padding-left: 12px;
        border-left: 2px dashed #ccc;
    }
    .condition-item {
        margin-bottom: 8px;
        padding: 6px;
        background: #f9f9f9;
        border-radius: 4px;
    }
    .action-row {
        margin: 8px 0;
    }
</style>
